<template>
  <memberSelect :screen="'1'" :back-screen="'1'">
    <template #content>
      <ContentWrap
        class="mb-0!"
        :class="[
          footer
            ? '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height)-10px)]'
            : '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-20px)]'
        ]"
        :bodyStyle="{ height: '100%' }"
      >
        <div class="flex flex-col !h-full">
          <el-row class="!w-full m-x-0! pb-10px" justify="space-between" :gutter="5">
            <el-col :xs="24" :sm="24" :md="12" :lg="18" :xl="20" class="flex! items-center">
              欠款: 总欠款金额{{ fenToYuan(totalArrears) }}元
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4">
              <el-button
                type="primary"
                class="!w-100%"
                v-if="selectedOrder.length > 0"
                @click="handleGoRepaymentCart"
              >
                批量还款
              </el-button>
            </el-col>
          </el-row>
          <el-scrollbar>
            <!-- 添加 row-key="id" 解决列数据中的 table#header 数据不刷新的问题  -->
            <el-table
              :data="orderArrearsList"
              row-key="id"
              :cell-style="{ padding: 0, borderBottom: 'none' }"
              :header-cell-style="{ padding: 0, borderBottom: 'none' }"
              :row-class-name="'table-row-class'"
            >
              <OrderTableColumn
                ref="orderListRef"
                :list="orderArrearsList"
                @selection-change="selectOrder"
              />
              <template #empty>
                <Empty />
              </template>
            </el-table>
            <!-- 分页 -->
            <Pagination
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.pageNo"
              :total="total"
              @pagination="getList"
            />
          </el-scrollbar>
        </div>
      </ContentWrap>
    </template>
  </memberSelect>
</template>
<script lang="ts" setup>
import memberSelect from '../components/member/user/memberSelect.vue' //会员选择
const message = useMessage() // 消息弹窗

import { useAppStore } from '@/store/modules/app'
import { OrderTableColumn } from './components'
import { formateArrObjData } from '@/utils/formatter'
const appStore = useAppStore()
const footer = computed(() => appStore.getFooter)
const orderArrearsList = ref<any>([])
const total = ref(2) // 列表的总页数
import * as TradeOrderApi from '@/api/mall/trade/order'
import { fenToYuan } from '@/utils'

// 表单搜索
const queryParams = ref({
  pageNo: 1, // 页数
  pageSize: 10, // 每页显示数量
  userId: undefined as any,
  typeClass: 6 //订单分类
})
/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'

const shopUserStore = useShopUserStoreWithOut()

const shopUser = computed(() => {
  return shopUserStore.getUser
})

/** 查询列表 */
const getList = async () => {
  try {
    // 统计
    queryParams.value.userId = shopUser.value.id
    const data = await TradeOrderApi.getOrderPage(unref(queryParams))
    orderArrearsList.value = data.list
    total.value = data.total
  } finally {
  }
}

const totalArrears = computed(() => {
  // 如果订单只有一条就取对应的总欠款，如果订单大于一条就说明是会员信息进入的欠款
  let arry = orderArrearsList.value
  if (arry.length > 0) {
    if (arry.length > 1) {
      return shopUser.value.arrearsPrice
    } else {
      return arry[0].leavePrice
    }
  } else {
    return 0
  }
})

const orderListRef = ref()
const selectedOrder = ref<any>([]) // 选中的商品 skuIds
const selectOrder = (val: any[]) => {
  selectedOrder.value = formateArrObjData(selectedOrder.value, val, 'no')
}
/**去购物车列表 */
const router = useRouter() // 路由对象
const handleGoRepaymentCart = () => {
  let items = [] as EmptyArrayType
  selectedOrder.value.forEach((element) => {
    console.log(element)
    element.val.forEach((item) => {
      items.push(item.id)
    })
  })
  console.log(items)
  // cartList.value.map((item) => {
  //   items.push({
  //     skuId: item.sku.skuId,
  //     count: item.count,
  //     cartId: item.id,
  //     categoryId: item.spu.categoryId
  //   })
  // })

  if (items.length > 0) {
    router.push({
      name: 'ShopPayCashierRepayment',
      query: {
        returnUrl: encodeURIComponent('/Repayment/Repayment'),
        items: JSON.stringify(items)
      }
    })
  } else {
    message.error('请先选择商品')
  }
} //去购物车
// 监听会员变化
watch(
  () => shopUser.value.id,
  () => {
    orderArrearsList.value = []
    if (shopUser.value.id > 0) {
      getList()
    }
  }
)
onMounted(async () => {
  await getList()
})
</script>
<style lang="scss" scoped>
:deep(.order-table-col > .cell) {
  padding: 0;
}
:deep(.table-row-class) {
  --el-table-row-hover-bg-color: transparent;
}
</style>
